package com.vanzo.talkie2;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;

import android_serialport_api.SerialPort;

/**
 * Created by tisen on 2018/1/9.
 */

public class ATHelper {

    private static final String TAG = "ATHelper";


    private static String AT_DMOCONNECT = "AT+DMOCONNECT";
    private static String AT_DMOSETGROUP = "AT+DMOSETGROUP";
    private static String AT_DMOSETMIC = "AT+DMOSETMIC";
    private static String AT_DMOSETVOLUME = "AT+DMOSETVOLUME";
    private static String AT_DMOSETVOX = "AT+DMOSETVOX";
    private static String AT_DMOSETAPC = "AT+DMOSETAPC";
    private static String AT_DMOPTT = "AT+DMOPTT";
    private static String AT_DMOSETVAFC = "AT+DMOSETVAFC";
    private static String AT_DMOGETVAFC = "AT+DMOGETVAFC";
    private static String AT_DMORDRSSI = "AT+DMORDRSSI";

    private Context context;
    private String fileName;

    protected Application mApplication;
    protected SerialPort mSerialPort;
    protected OutputStream mOutputStream;
    private InputStream mInputStream;
    private ReadThread mReadThread;

    private Callback callback;

    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                int size;
                try {
                    byte[] buffer = new byte[128];
                    if (mInputStream == null) return;
                    size = mInputStream.read(buffer);
                    if (size > 0) {
                        Log.d("zts", "size = " + size);
                        onDataReceived(buffer, size);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }


    private void onDataReceived(final byte[] buffer, final int size) {
        temp.append(new String(buffer, 0, size));
        if (temp.toString().endsWith("\r\n")) {
            if (callback != null) {
                callback.callback(temp.toString());
                callback = null;
            }
            Log.d("zts", temp.toString());
            temp = new StringBuilder();
        } else {

        }
    }

    private StringBuilder temp = new StringBuilder();

    public ATHelper(Context context, Application application) {
        this.context = context;
        init(application);
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public void init(Application application) {
        mApplication = application;
        try {
            mSerialPort = mApplication.getSerialPort();
            mOutputStream = mSerialPort.getOutputStream();
            mInputStream = mSerialPort.getInputStream();

			/* Create a receiving thread */
        } catch (SecurityException e) {
            DisplayError(R.string.error_security);
        } catch (IOException e) {
            DisplayError(R.string.error_unknown);
        } catch (InvalidParameterException e) {
            DisplayError(R.string.error_configuration);
        }
    }

    private void DisplayError(int resourceId) {
        AlertDialog.Builder b = new AlertDialog.Builder(context);
        b.setTitle("Error");
        b.setMessage(resourceId);
        b.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        b.show();
    }

    public void setCon(Callback callback) {
        String atCmd = AT_DMOCONNECT;
        sendATCmd(atCmd, callback);
    }


    public void setGroup(int mode, int gbw, String tfv, String rfv, String txcxcss, String rxcxcss, String sq, int power, Callback callback) {
        String atCmd = AT_DMOSETGROUP + "=" + mode
                + "," + gbw
                + "," + tfv
                + "," + rfv
                + "," + txcxcss
                + "," + rxcxcss
                + "," + sq
                + "," + power;
        sendATCmd(atCmd, callback);
    }

    public void setMic(int mode, Callback callback) {
        String atCmd = AT_DMOSETMIC + "=" + mode;
        sendATCmd(atCmd, callback);
    }

    public void setVolume(int volume, Callback callback) {
        String atCmd = AT_DMOSETVOLUME + "=" + volume;
        sendATCmd(atCmd, callback);
    }

    public void setVox(int vox, Callback callback) {
        String atCmd = AT_DMOSETVOX + "=" + vox;
        sendATCmd(atCmd, callback);
    }

    public void setApc(int apc, Callback callback) {
        String atCmd = AT_DMOSETAPC + "=" + apc;
        sendATCmd(atCmd, callback);
    }

    public void setPtt(int ptt, Callback callback) {
        String atCmd = AT_DMOPTT + "=" + ptt;
        sendATCmd(atCmd, callback);
    }

    public void setAfc(int afc, Callback callback) {
        String atCmd = AT_DMOSETVAFC + "=" + afc;
        sendATCmd(atCmd, callback);
    }

    public void getAfc(Callback callBack) {
        String atCmd = AT_DMOGETVAFC;
        sendATCmd(atCmd, callBack);
    }

    public void getRssi(Callback callBack) {
        String atCmd = AT_DMORDRSSI;
        sendATCmd(atCmd, callBack);
    }


    public void sendATCmd(String atCmd, Callback callback) {
        Log.d("zts", atCmd);
        if (mReadThread == null) {
            mReadThread = new ReadThread();
            mReadThread.start();
        }
        this.callback = callback;
        int i;
        CharSequence t = atCmd + "\r";
        Log.i(TAG, "sendATCmd = " + t);
        char[] text = new char[t.length()];
//                send.setEnabled(false);
        for (i = 0; i < t.length(); i++) {
            text[i] = t.charAt(i);
        }
        try {
            mOutputStream.write(new String(text).getBytes());
            mOutputStream.write('\n');
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public interface Callback {
        void callback(String result);
    }
}
